<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              组织名称：<el-input placeholder="请输入内容" v-model="selectForm.orgName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              负责人：<el-input placeholder="请输入内容" v-model="selectForm.firstResponsibilityName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              负责人联系方式：<el-input placeholder="请输入内容" v-model="selectForm.firstResponsibilityPhone" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogFormVisible"
            class="custom-dialog_style_twoLine"
            :before-close="cancel"
            :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="formData" label-width="50%">
              <el-form-item label="组织名称：" prop="orgName" label-width="30%">
                <el-input v-model="formData.orgName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="组织编号：" label-width="30%">
                <el-input v-model="formData.orgCode" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="部门：" prop="deptIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    clearable
                    change-on-select
                    :props="areaProps"
                    v-model="formData.deptIdArr"
                    @change="deptIdChangeEvt">
                  </el-cascader>
                </div>
              </el-form-item>
              <el-form-item label="第一责任人：" label-width="30%">
                <el-select v-model="formData.firstResponsibilityId" clearable filterable allow-create placeholder="请选择" @change="changeGetPhone">
                  <el-option v-for="(item,index) in ResponsibilityOption" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="第一责任人联系方式：" label-width="30%">
                <el-input readonly v-model="formData.firstResponsibilityPhone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="第一负责人：" label-width="30%">
                <el-select v-model="formData.firstChargeId" clearable filterable allow-create placeholder="请选择">
                  <el-option v-for="(item,index) in ResponsibilityOption" :key="index" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="图片：" class="custom-img-container">
                <app-upload ref="appUpload" v-model="formData.picture" ></app-upload>
              </el-form-item>
              <el-form-item label="" label-width="30%">
              </el-form-item>
              <el-form-item label="备注：" class="custom-textarea-container" label-width="30%">
                <el-input type="textarea" v-model="formData.remark"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="30%">
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppUpload from '@/components/AppUpload'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import {getAllRegion, getAllRegionObj} from '@/utils/region'
import {getUserDeptTree} from '@/utils/SessionDataUtil'
import {findOrganization, createOrganization, updateOrganization, deleteOrganization, findDeptMemberList, getUser} from '@/http/AppApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'orgName', label: '组织名称' },
        { prop: 'deptAllId', label: '所属部门', formatter: this.deptNameFormatter },
        // { prop: 'firstResponsibilityId', label: '负责人', formatter: this.ResponsibilityNameFormatter },
        { prop: 'firstResponsibilityName', label: '负责人' },
        { prop: 'firstResponsibilityPhone', label: '联系方式' },
        { prop: 'remark', label: '简介' }
      ],
      tableDada: [],
      formData: {},
      selectForm: {},
      ResponsibilityTemp: [],
      areaProps: {
        label: 'name',
        value: 'id'
      },
      rules: {
        orgName: [
          { required: true, message: '请输入组织名称', trigger: 'blur' }
        ],
        deptIdArr: [
          { required: true, message: '请选择部门', trigger: 'blur' }
        ]
      },
      ResponsibilityOption: []
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    AppUpload
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
  },
  methods: {
    deptNameFormatter (row, column) {
      let len = row.deptAllId.split(',').length
      let deptData = {}
      deptData.id = row.deptAllId.split(',')[len - 1]
      deptData.items = this.treeData
      let allid = getAllRegionObj(deptData)
      let name = ''
      for (let i = 0; i < allid.length; i++) {
        const element = allid[i]
        name += element.name + ','
      }
      return name
    },
    ResponsibilityNameFormatter (row, column) {
      this.getDeptMemberOption(row.deptId)
      let name = ''
      for (const key in this.ResponsibilityOption) {
        if (this.ResponsibilityOption.hasOwnProperty(key)) {
          if (this.ResponsibilityOption[key].id === row.firstResponsibilityId) {
            name = this.ResponsibilityOption[key].name
            if (name !== '') break
          }
        }
      }
      return name
    },
    getDeptMemberOption (deptId) {
      let m = this
      findDeptMemberList(deptId).then(resp => {
        if (resp.code && resp.code === '200') {
          m.ResponsibilityOption = resp.data
        }
      })
    },
    deptIdChangeEvt (val) {
      if (val && val.length !== 0) {
        let index = val.length - 1
        let deptId = val[index]
        this.getDeptMemberOption(deptId)
      } else {
        this.ResponsibilityOption = []
      }
    },
    getTreeData () {
      let data = getUserDeptTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
        } else {
          if (this.formData.deptIdArr && this.formData.deptIdArr.length > 0) {
            let len = this.formData.deptIdArr.length - 1
            let deptData = {}
            deptData.id = this.formData.deptIdArr[len]
            deptData.isGetAllId = true
            deptData.items = this.treeData
            this.formData.deptAllId = getAllRegion(deptData)
          } else {
            this.formData.deptAllId = ''
          }
          let m = this
          if (m.formData.id) {
            updateOrganization(m.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                m.dialogFormVisible = false
                m.$message({
                  type: 'success',
                  message: '修改成功'
                })
                m.getTableData()
              }
            })
          } else {
            createOrganization(m.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                m.dialogFormVisible = false
                m.$message({
                  type: 'success',
                  message: '添加成功'
                })
                m.getTableData()
              } else {
                m.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteOrganization(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      let m = this
      findOrganization(param).then(resp => {
        if (resp) {
          if (resp.code && resp.code === '200') {
            let pdata = resp.data
            let name = ''
            for (let i = 0; i < pdata.items.length; i++) {
              const element = pdata.items[i];
              (function (i) {
                findDeptMemberList(pdata.items[i].deptId).then(resp => {
                  if (resp.code && resp.code === '200') {
                    m.ResponsibilityTemp = resp.data
                    for (let j = 0; j < m.ResponsibilityTemp.length; j++) {
                      const ele = m.ResponsibilityTemp[j]
                      name = ele.name
                      if (element.firstResponsibilityId === ele.id) {
                        m.$set(pdata.items[i], 'firstResponsibilityName', name)
                        m.tableData = pdata.items
                        m.pageData = pdata
                      }
                    }
                  }
                })
                getUser(pdata.items[i].firstResponsibilityId).then(resp => {
                  if (resp.code && resp.code === '200') {
                    let data = resp.data
                    m.$set(m.formData, 'firstResponsibilityPhone', data.phone)
                  }
                })
              })(i)
            }
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.deptIdArr) {
            let arr = this.formData.deptIdArr
            this.formData = {}
            this.$set(this.formData, 'deptIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          this.dialogTitle = callbackData.btnType === 'put' ? '修改' : '查看'
          let obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          if (!this.formData.deptId || this.formData.deptId === '') {
            this.$message({
              type: 'info',
              message: '此数据格式有误'
            })
            return ''
          }
          let deptData = {}
          deptData.id = this.formData.deptId
          deptData.items = this.treeData
          let deptIdArr = getAllRegion(deptData)
          this.$set(this.formData, 'deptIdArr', deptIdArr)
          this.getDeptMemberOption(this.formData.deptId)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else if (rows.length === 0) {
        this.currentSelectedData = []
      }
    },
    changeGetPhone (val) {
      getUser(val).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          console.log(data)
          this.$set(this.formData, 'firstResponsibilityPhone', data.phone)
        }
      })
    },
    appTreeClick (data) {
      let deptData = {}
      deptData.id = data.id
      deptData.items = this.treeData
      let deptIdArr = getAllRegion(deptData)
      this.$set(this.formData, 'deptIdArr', deptIdArr)
      this.selectForm.offset = 0
      this.selectForm.deptId = data.id
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    }
  }
}
</script>

<style scoped>
  .el-table th{
    background-color: #409EFF;
    color: #333;
  }
  .ral-latitude{
    position: relative;
  }
  #coordinateChoice{
    color: red;
    font-size: 14px;
    cursor: pointer;
    position: absolute;
    top: 0;
    right: 18px;
  }
</style>
